<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- 当前用户总积分显示 -->
      <div class="points-info">
        <span class="points-label">我的积分：</span>
        <span class="points-value">{{ currentUserPoints }}</span>
      </div>
      <!--      <el-input v-model="listQuery.user_id" placeholder="用户ID" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />-->
      <el-input v-model="listQuery.process_name" placeholder="流程名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="积分类型" clearable style="width: 120px" class="filter-item">
        <el-option label="获取积分" value="1" />
        <el-option label="消耗积分" value="2" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item"
        style="width: 340px"
        @change="handleDateChange"
      />
      <el-button v-permisaction="['points:history:list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-download" :loading="exportLoading" @click="handleExport">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户ID" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程名称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.process_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单ID" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.work_order_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="变更积分" width="110px" align="center">
        <template slot-scope="{row}">
          <span :class="row.points > 0 ? 'text-success' : 'text-danger'">{{ row.points > 0 ? '+' : '' }}{{ row.points }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分类型" width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type === 1 ? 'success' : 'warning'">
            {{ row.type === 1 ? '获取积分' : '消耗积分' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="备注" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.reason }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <el-button v-permisaction="['points:history:detail']" type="primary" size="mini" @click="handleDetail(row)">-->
      <!--            详情-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 详情对话框 -->
    <el-dialog :title="'积分历史详情'" :visible.sync="dialogDetailVisible" width="600px">
      <el-form ref="detailForm" :model="detailData" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID:">
          <span>{{ detailData.id }}</span>
        </el-form-item>
        <el-form-item label="用户ID:">
          <span>{{ detailData.user_id }}</span>
        </el-form-item>
        <el-form-item label="流程名称:">
          <span>{{ detailData.process_name }}</span>
        </el-form-item>
        <el-form-item label="工单ID:">
          <span>{{ detailData.work_order_id }}</span>
        </el-form-item>
        <el-form-item label="变更积分:">
          <span :class="detailData.points > 0 ? 'text-success' : 'text-danger'">{{ detailData.points > 0 ? '+' : '' }}{{ detailData.points }}</span>
        </el-form-item>
        <el-form-item label="积分类型:">
          <el-tag :type="detailData.type === 1 ? 'success' : 'warning'">
            {{ detailData.type === 1 ? '获取积分' : '消耗积分' }}
          </el-tag>
        </el-form-item>
        <el-form-item label="备注:">
          <span>{{ detailData.reason }}</span>
        </el-form-item>
        <el-form-item label="创建时间:">
          <span>{{ detailData.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
        <el-form-item label="更新时间:">
          <span>{{ detailData.update_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDetailVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPointsHistoryList, getCurrentUserPoints } from '@/api/points.js'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { exportPointsHistoryToExcel, getAllPointsHistoryData } from '@/utils/export'

export default {
  name: 'PointsHistory',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      currentUserPoints: 0,
      listQuery: {
        page: 1,
        limit: 20,
        user_id: undefined,
        process_name: undefined,
        type: undefined,
        start_time: undefined,
        end_time: undefined,
        sort: '+id'
      },
      dateRange: [],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      dialogDetailVisible: false,
      detailData: {},
      exportLoading: false
    }
  },
  created() {
    this.getCurrentUserPoints()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getPointsHistoryList(this.listQuery).then(response => {
        console.log('API Response:', response)
        if (response.data) {
          // 后端返回的是pagination.Paginator结构，包含data和total_count字段
          this.list = response.data.data || []
          this.total = response.data.total_count || 0
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(error => {
        console.error('API Error:', error)
        this.list = []
        this.total = 0
        this.listLoading = false
        this.$message.error('获取积分历史数据失败')
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDateChange(value) {
      if (value && value.length === 2) {
        this.listQuery.start_time = value[0]
        this.listQuery.end_time = value[1]
      } else {
        this.listQuery.start_time = undefined
        this.listQuery.end_time = undefined
      }
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleDetail(row) {
      this.detailData = Object.assign({}, row)
      this.dialogDetailVisible = true
    },
    async handleExport() {
      this.exportLoading = true
      try {
        // 构建查询参数，获取所有数据
        const queryParams = {
          ...this.listQuery
        }

        // 获取所有积分历史数据
        const allData = await getAllPointsHistoryData(getPointsHistoryList, queryParams)

        // 导出到Excel
        const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
        const filename = `积分历史记录_${timestamp}`

        exportPointsHistoryToExcel(allData, filename)

        this.$message.success('导出成功！')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败，请重试')
      } finally {
        this.exportLoading = false
      }
    },
    getCurrentUserPoints() {
      getCurrentUserPoints().then(response => {
        if (response.data) {
          this.currentUserPoints = response.data.total_points || 0
        }
      }).catch(error => {
        console.error('获取用户积分失败:', error)
        this.$message.error('获取用户积分失败')
      })
    }
  }
}
</script>

<style scoped>
.text-success {
  color: #67c23a;
}
.text-danger {
  color: #f56c6c;
}

.points-info {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.points-label {
  font-size: 14px;
  color: #606266;
  margin-right: 8px;
}

.points-value {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
}
</style>
